<?php

namespace App\Crontab;

use App\Model\Mysql\CouponModel;
use App\Model\Mysql\UserCouponModel;
use EasySwoole\EasySwoole\Crontab\AbstractCronTask;

class CouponOverdue extends AbstractCronTask
{

    public static function getRule(): string
    {
        return '*/1 * * * *';
    }

    public static function getTaskName(): string
    {
        return 'couponOverdue';
    }

    /**
     * 优惠券过期处理
     * @param int $taskId
     * @param int $workerIndex
     */
    function run(int $taskId, int $workerIndex)
    {
        $coupon = CouponModel::getList(['operate_type' => 0], ['id', 'end_time']);

        foreach ($coupon as $value) {
            if ($value['end_time'] < time()) {
                CouponModel::editData(['operate_type' => 1, 'status' => 0], ['id' => $value['id']]);
                UserCouponModel::editData(['status' => 4], ['coupon_id' => $value['id'], 'status' => 1]);
            }
        }
    }

    function onException(\Throwable $throwable, int $taskId, int $workerIndex)
    {
        echo $throwable->getMessage();
    }
}
